<template>
  <div class="dataTemplate">

    <p style="font-weight: bold;">
      <span>当前模板为：</span>
      <el-link type="primary" style="font-size: 16px;font-weight: bold;" v-if="templateName">{{ templateName
      }}</el-link>
      <el-link type="danger" style="font-size: 16px;font-weight: bold;" v-else>暂无模板</el-link>
    </p>
    <el-upload ref="upload" class="upload-demo" :limit="1" accept=".xlsx" drag :action="action" multiple
      :headers="headers" :on-success="handleAvatarSuccess" :on-error="handleAvatarError" :before-upload="handleBefore">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    </el-upload>
    <div v-if="sheetList.length > 0">
      <h2>导入的子sheet</h2>
      <div style="display: flex;gap: 20px;">
        <el-tag size="medium" v-for="item in sheetList" :key="item"> {{ item }}</el-tag>
      </div>


    </div>
    <div v-if="errorData.length > 0">
      <div style="font-size: 18px; font-weight: bold; color:#ff4949;">唯一值重复</div>
      <p v-for="item in errorData">{{ item }}</p>
    </div>
  </div>
</template>
<script>
import { getToken } from '@/utils/auth'
import URL from '@/api/api'
import { Message, Loading } from 'element-ui'
import DatasetApi from "../api/Dataset.js"

export default {
  data() {
    return {
      action: URL + "/excel/upload",
      headers: {
        Authorization: getToken(),
      },
      templateName: "",
      sheetList: [],
      loading: null,
      errorData: []
    }
  },
  methods: {
    handleBefore() {

      this.loading = Loading.service({
        lock: true,
        text: '文件上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.8)'
      })
    },
    handleAvatarSuccess(resp) {
      if (resp.code === 200) {
        this.templateName = resp.data.fileName
        this.sheetList = resp.data.sheetNames
        this.errorData = []
        Message.success("上传成功")
      } else {
        this.templateName = ''
        this.sheetList = []
        this.errorData = resp.data
        Message.error("模板上传失败，格式错误")
      }
      this.$refs.upload.clearFiles()
      this.loading.close()
    },
    handleAvatarError(error) {
      this.loading.close()
      Message.error("模板上传失败，格式错误!")
    }
  },
  mounted() {

    DatasetApi.getFileNameAndSheetNames().then(res => {
      if (res.data.code == 200) {
        this.templateName = res.data.data.fileNames[0]
        this.sheetList = res.data.data.sheetNames
      }
    })
  }
}
</script>
<style>
.dataTemplate {
  padding: 20px;
}
</style>